// 默认快捷方式数据
const defaultShortcuts = [
    { name: 'Google', url: 'https://google.com', icon: 'https://www.google.com/favicon.ico' },
    { name: 'GitHub', url: 'https://github.com', icon: 'https://github.com/favicon.ico' },
    { name: 'YouTube', url: 'https://youtube.com', icon: 'https://www.youtube.com/favicon.ico' },
    { name: 'Bilibili', url: 'https://bilibili.com', icon: 'https://www.bilibili.com/favicon.ico' },
    { name: '知乎', url: 'https://zhihu.com', icon: 'https://static.zhihu.com/heifetz/favicon.ico' },
    { name: '微博', url: 'https://weibo.com', icon: 'https://weibo.com/favicon.ico' },
    { name: '淘宝', url: 'https://taobao.com', icon: 'https://www.taobao.com/favicon.ico' },
    { name: '京东', url: 'https://jd.com', icon: 'https://www.jd.com/favicon.ico' }
];

// 全局变量
let shortcuts = [];
let editingIndex = -1;
let draggedElement = null;

// DOM 元素
const shortcutsGrid = document.getElementById('shortcutsGrid');
const searchInput = document.getElementById('searchInput');
const addBtn = document.getElementById('addBtn');
const addModal = document.getElementById('addModal');
const closeModal = document.getElementById('closeModal');
const cancelBtn = document.getElementById('cancelBtn');
const shortcutForm = document.getElementById('shortcutForm');
const modalTitle = document.getElementById('modalTitle');
const nameInput = document.getElementById('nameInput');
const urlInput = document.getElementById('urlInput');
const iconInput = document.getElementById('iconInput');

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    loadShortcuts();
    renderShortcuts();
    setupEventListeners();
});

// 加载快捷方式
function loadShortcuts() {
    const saved = localStorage.getItem('shortcuts');
    if (saved) {
        shortcuts = JSON.parse(saved);
    } else {
        shortcuts = [...defaultShortcuts];
        saveShortcuts();
    }
}

// 保存快捷方式到本地存储
function saveShortcuts() {
    localStorage.setItem('shortcuts', JSON.stringify(shortcuts));
}

// 渲染快捷方式
function renderShortcuts(filterText = '') {
    const filtered = shortcuts.filter(shortcut => 
        shortcut.name.toLowerCase().includes(filterText.toLowerCase())
    );

    shortcutsGrid.innerHTML = '';

    if (filtered.length === 0) {
        shortcutsGrid.innerHTML = `
            <div class="empty-state" style="grid-column: 1 / -1;">
                <i class="fas fa-search"></i>
                <p>没有找到匹配的快捷方式</p>
            </div>
        `;
        return;
    }

    filtered.forEach((shortcut, index) => {
        const shortcutElement = createShortcutElement(shortcut, index);
        shortcutsGrid.appendChild(shortcutElement);
    });
}

// 创建快捷方式元素
function createShortcutElement(shortcut, index) {
    const div = document.createElement('div');
    div.className = 'shortcut-item';
    div.draggable = true;
    div.dataset.index = index;

    const iconHtml = shortcut.icon 
        ? `<img src="${shortcut.icon}" alt="${shortcut.name}" onerror="this.style.display='none'; this.nextElementSibling.style.display='block';">`
        : '';

    div.innerHTML = `
        <div class="shortcut-icon">
            ${iconHtml}
            <i class="fas fa-globe" style="${shortcut.icon ? 'display: none;' : ''}"></i>
        </div>
        <div class="shortcut-name">${shortcut.name}</div>
        <button class="delete-btn" onclick="deleteShortcut(${index})">
            <i class="fas fa-times"></i>
        </button>
    `;

    // 点击打开网站
    div.addEventListener('click', (e) => {
        if (!e.target.classList.contains('delete-btn') && !e.target.parentElement.classList.contains('delete-btn')) {
            window.open(shortcut.url, '_blank');
        }
    });

    // 拖拽事件
    div.addEventListener('dragstart', handleDragStart);
    div.addEventListener('dragend', handleDragEnd);
    div.addEventListener('dragover', handleDragOver);
    div.addEventListener('drop', handleDrop);

    return div;
}

// 删除快捷方式
function deleteShortcut(index) {
    if (confirm('确定要删除这个快捷方式吗？')) {
        shortcuts.splice(index, 1);
        saveShortcuts();
        renderShortcuts(searchInput.value);
    }
}

// 搜索功能
searchInput.addEventListener('input', (e) => {
    renderShortcuts(e.target.value);
});

// 设置事件监听器
function setupEventListeners() {
    // 添加按钮
    addBtn.addEventListener('click', () => {
        editingIndex = -1;
        modalTitle.textContent = '添加快捷方式';
        shortcutForm.reset();
        addModal.style.display = 'block';
    });

    // 关闭模态框
    closeModal.addEventListener('click', () => {
        addModal.style.display = 'none';
    });

    cancelBtn.addEventListener('click', () => {
        addModal.style.display = 'none';
    });

    // 点击模态框外部关闭
    window.addEventListener('click', (e) => {
        if (e.target === addModal) {
            addModal.style.display = 'none';
        }
    });

    // 表单提交
    shortcutForm.addEventListener('submit', (e) => {
        e.preventDefault();
        
        const name = nameInput.value.trim();
        let url = urlInput.value.trim();
        const icon = iconInput.value.trim();

        // 确保URL有协议
        if (!url.startsWith('http://') && !url.startsWith('https://')) {
            url = 'https://' + url;
        }

        const shortcut = { name, url, icon: icon || '' };

        if (editingIndex >= 0) {
            shortcuts[editingIndex] = shortcut;
        } else {
            shortcuts.push(shortcut);
        }

        saveShortcuts();
        renderShortcuts(searchInput.value);
        addModal.style.display = 'none';
    });

    // 键盘快捷键
    document.addEventListener('keydown', (e) => {
        if (e.key === '/' && !e.ctrlKey && !e.metaKey) {
            e.preventDefault();
            searchInput.focus();
        }
        if (e.key === 'Escape') {
            addModal.style.display = 'none';
            searchInput.blur();
        }
    });
}

// 拖拽功能
function handleDragStart(e) {
    draggedElement = this;
    this.classList.add('dragging');
    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('text/html', this.innerHTML);
}

function handleDragEnd(e) {
    this.classList.remove('dragging');
    document.querySelectorAll('.shortcut-item').forEach(item => {
        item.classList.remove('drag-over');
    });
}

function handleDragOver(e) {
    if (e.preventDefault) {
        e.preventDefault();
    }
    e.dataTransfer.dropEffect = 'move';
    
    const afterElement = getDragAfterElement(shortcutsGrid, e.clientY);
    if (afterElement == null) {
        shortcutsGrid.appendChild(draggedElement);
    } else {
        shortcutsGrid.insertBefore(draggedElement, afterElement);
    }
    
    return false;
}

function handleDrop(e) {
    if (e.stopPropagation) {
        e.stopPropagation();
    }
    
    if (draggedElement !== this) {
        updateShortcutsOrder();
    }
    
    return false;
}

function getDragAfterElement(container, y) {
    const draggableElements = [...container.querySelectorAll('.shortcut-item:not(.dragging)')];
    
    return draggableElements.reduce((closest, child) => {
        const box = child.getBoundingClientRect();
        const offset = y - box.top - box.height / 2;
        
        if (offset < 0 && offset > closest.offset) {
            return { offset: offset, element: child };
        } else {
            return closest;
        }
    }, { offset: Number.NEGATIVE_INFINITY }).element;
}

function updateShortcutsOrder() {
    const newOrder = [];
    document.querySelectorAll('.shortcut-item').forEach(item => {
        const oldIndex = parseInt(item.dataset.index);
        newOrder.push(shortcuts[oldIndex]);
    });
    
    shortcuts = newOrder;
    saveShortcuts();
    renderShortcuts(searchInput.value);
}

// 导出/导入功能（可选）
function exportShortcuts() {
    const dataStr = JSON.stringify(shortcuts, null, 2);
    const dataBlob = new Blob([dataStr], { type: 'application/json' });
    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = 'shortcuts.json';
    link.click();
}

function importShortcuts(file) {
    const reader = new FileReader();
    reader.onload = (e) => {
        try {
            const imported = JSON.parse(e.target.result);
            if (Array.isArray(imported)) {
                shortcuts = imported;
                saveShortcuts();
                renderShortcuts();
                alert('导入成功！');
            }
        } catch (error) {
            alert('导入失败：无效的文件格式');
        }
    };
    reader.readAsText(file);
}

// 添加右键菜单（可选）
document.addEventListener('contextmenu', (e) => {
    if (e.target.closest('.shortcut-item')) {
        e.preventDefault();
        // 可以在这里添加右键菜单
    }
});
